import { useState, useEffect } from 'react';
import { Select, Tag } from 'antd';
import DropDownRender from './DropRender';
import { getPersons } from './service';
import { InbizIcon, deepClone } from '@inbiz/utils';
import { observer } from '@formily/react';
import { getMessage } from '@inbiz/react';
import { getMemberIconByKey } from '@inbiz/basic/MemberSelect';
const { Option } = Select;

const getTabKeyByData = (data) => {
  if (data.hasOwnProperty('DeptCode')) {
    return 'department';
  } else if (data.hasOwnProperty('PositionCode')) {
    return 'position';
  } else if (data.hasOwnProperty('GroupType')) {
    return 'group';
  } else if (data.hasOwnProperty('UserCode')) {
    return 'user';
  } else {
    return '';
  }
};

export default observer((props: any) => {
  const { disabled, selected, $selected, width, reset, showArrow, showModal, issign } = props;
  const [options, $options] = useState<any[]>([
    {
      name: getMessage('processButton.oneCharacter'),
      id: getMessage('processButton.oneCharacter'),
      disabled: true,
    },
  ]);
  const [value, $value] = useState([]);
  const [searchValue, $searchValue] = useState('');
  const [open, $open] = useState(false);

  const standardData = (arr) => {
    return arr.map((item) => ({
      ...item,
      label: item.name || item.Name,
      key: item.id || item.Id,
      id: item.id || item.Id,
      name: item.name || item.Name,
      identityid: item.IdentityId || item.identityid,
      userkey: getTabKeyByData(item),
    }));
  };
  const onChange = (val) => {
    const arr = selected.filter((item) => val.some((ele) => ele.value == item.id));

    $value(standardData(arr));
    $selected(arr);
  };
  const onClear = () => {
    if (reset) {
      reset();
    }
    $value([]);
    $selected([]);
    $options([]);
  };

  const onSearch = (searchContent: string) => {
    if (searchContent.trim()) {
      $open(true);
      $searchValue(searchContent);
      getPersons({ searchContent }).then((res) => {
        if (res && res.UserList) {
          if (res.UserList.length) {
            $options(standardData(res.UserList.slice(0, 5)));
          } else {
            $options([{ name: getMessage('processButton.noSearchData'), id: '', disabled: true }]);
          }
        } else {
          $open(false);
        }
      });
    }
  };
  const onSelect = (value) => {
    const obj = options.find((ele) => ele.id == value) || {};
    $selected(obj);
  };

  const operateItem = (item) => {
    if (!item.disabled) {
      const newValue = selected || [];
      const index = newValue.map((v) => v.id).indexOf(item.id);
      if (index == -1) {
        newValue.push(item);
        $open(false);
      } else {
        newValue.splice(index, 1);
      }

      $selected(newValue);
      $value(newValue.map((item) => ({ ...item, label: item.name, key: item.id })));
    }
  };

  useEffect(() => {
    if (selected.length > 0) {
      $value(standardData(selected));
    } else {
      $value([]);
    }
  }, [selected]);

  return (
    <Select
      showSearch
      style={{ width: width }}
      placeholder={getMessage('processButton.searchUser')}
      value={value}
      onChange={onChange}
      onSearch={onSearch}
      filterOption={false}
      labelInValue
      // onClear={() => onClear()}
      disabled={disabled}
      defaultValue={['']}
      open={open}
      showArrow={showArrow}
      placement="bottomLeft"
      mode="multiple"
      onBlur={(e) => {
        // $options([]);
        $searchValue('');
        setTimeout(() => {
          $open(false);
        }, 1000);
      }}
      suffixIcon={<InbizIcon type="icon-ic-shouqisanjiao" onClick={showModal} />}
      dropdownRender={(menu) => {
        return (
          <DropDownRender
            iconRender={(item) => getMemberIconByKey(item.key)}
            searchValue={searchValue}
            value={selected && selected.map((v) => v.id)}
            data={options}
            onItemClick={operateItem}
            extra={(item) => {
              return item.DepartmentName || item.departmentname;
            }}
          />
        );
      }}
    >
      {deepClone(options).map((item, index) => {
        return (
          <Option key={item.id} disabled={item.disabled} value={item.id}>
            {item.name}
          </Option>
        );
      })}
    </Select>
  );
});
